/************************************************************
 * DS_TABLE.CPP                                    12.01.2009
 *
 * .
 ************************************************************/

#include "ds_table.h"
#include "m3d.h"

namespace ds {

/**************************************************************************
* TABLE::GetTableInfo()                                                   *
*                                                                         *
**************************************************************************/
void TABLE::GetTableInfo(TABLE_INFO & info) const
{
   info.width  = 0;
   info.height = 0;
   info.rowHeight.Clear();
   info.rowHeight.Resize(GetRowCount(), 1);

   for (int i = 0; i < GetRowCount(); ++i) {
      const TABLE_ROW & row = GetRow(i);

      for (int k = 0; k < row.GetCellCount(); ++k) {
         m3dUpdateMax(info.rowHeight[i], row.GetCell(k).GetCount());
      }

      m3dUpdateMax(info.width, row.GetCellCount());
      info.height += info.rowHeight[i];
   }
}

/**************************************************************************
* TABLE::ToCSVFormat()                                                    *
*                                                                         *
**************************************************************************/
dsSTRING TABLE::ToCSVFormat(void) const
{
   dsSTRING res;

   TABLE_INFO info;
   GetTableInfo(info);

   for (int i = 0; i < GetRowCount(); ++i) {
      const TABLE_ROW & row = GetRow(i);

      for (int p = 0; p < info.rowHeight[i]; ++p) {
         for (int k = 0; k < info.width; ++k) {
            if (k < row.GetCellCount()) {
               const TABLE_CELL & cell = row.GetCell(k);

               if (p < cell.GetCount()) {
                  res += "\"";
                  
                  // Trim & remove double-new lines
                  dsSTRING str = cell.Get(p);
                  str.Trim();

                  int counter = 0;
                  for (int index = 0; index + 1 < str.Length(); ++index) {
                     if (str[index] == '\n' && str[index + 1] == '\n') {
                        str.Erase(index, 1);
                        --index;
                        continue;
                     }

                     if (str[index] == '\n' && ++counter > 10) {
                        str = str.SubStr(0, index + 1);
                        break;
                     }
                  }

                  res += str;
                  res += "\"";
               }
            }

            if (k + 1 < info.width) {
               res += ";";
            }
         }

         res += "\n";
      }
   }

   return res;
}

}


//
// End-of-file DS_TABLE.CPP
//
